<?php

/**
 * 前台会员通行证
 * File Name：PassportAdminService.php
 * File Encoding：UTF-8
 * File New Time：2014-4-29 9:22:06
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class UserPassport extends CApplicationComponent implements ArrayAccess {

    //存储用户uid的Key
    const key = 'user_id';

    //错误密码
    protected $error = NULL;
    //用户信息
    protected static $userInfo = array();
    //返回地址
    public $returnUrl = '/user/info/index.html';

    public function __get($name) {
        if (isset(self::$userInfo[$name])) {
            return self::$userInfo[$name];
        } else {
            $userInfo = $this->getInfo();
            if (!empty($userInfo)) {
                return $userInfo[$name];
            }
            return NULL;
        }
    }

    /**
     * 获取错误信息
     * @return type
     */
    public function getError() {
        return $this->error;
    }

    /**
     * 获取当前登录用户资料
     * @return array 
     */
    public function getInfo() {
        if (empty(self::$userInfo)) {
            $uid = $this->getCookieUid();
            self::$userInfo = $this->getLocalUser((int) $uid);
            if (!empty(self::$userInfo)) {
                self::$userInfo['id'] = self::$userInfo['uid'];
                self::$userInfo['name'] = self::$userInfo['username'];
            } else {
                $cookie = Yii::app()->request->getCookies();
                unset($cookie[self::key]);
            }
        }
        return !empty(self::$userInfo) ? self::$userInfo : false;
    }

    /**
     * 获取cookie中的id
     * @return boolean
     */
    public function getCookieUid() {
        $cookie = Yii::app()->request->getCookies();
        if (!isset($cookie[self::key])) {
            return false;
        }
        $ciphertext = $cookie[self::key]->value;
        if (empty($ciphertext)) {
            return false;
        }
        $uid = Encrypt::authcode($ciphertext);
        if (empty($uid)) {
            return false;
        }
        return $uid;
    }

    /**
     * 检查是否已经登录，有登录返回登录uid
     * @return boolean
     */
    public function isLogged() {
        //获取cookie中的用户id
        $uid = $this->getCookieUid();
        if (empty($uid) || (int) $uid < 1) {
            return false;
        }
        return $uid;
    }

    /**
     * 登录后台并进行身份验证
     * @param type $identifier 验证条件，直接uid，用户名
     * @param type $password 明文密码
     * @param type $is_remeber_me 记录时间
     * @return boolean
     */
    public function login($identifier, $password, $is_remeber_me = 2592000) {
        if (empty($identifier) || empty($password)) {
            $this->error = '帐号或者密码为空！';
            return false;
        }
        //进行登录验证
        $userInfo = $this->getLocalUser($identifier, $password);
        if (empty($userInfo)) {
            return false;
        }
//        if (empty($userInfo['status'])) {
//            $this->error = '您的帐号还没有激活，无法登录！';
//            return false;
//        }
        if ($userInfo['is_lock']) {
            $this->error = $userInfo['is_locklog'] ? $userInfo['is_locklog'] : '您的帐号已被锁定，无法登录！';
            return false;
        }
        //增加登录送积分
        /*        $last_login_time = date('Ymd', $userInfo['lastlogintime']);
          $now = date('Ymd');
          if ($now != $last_login_time) {
          if (MembersModel::model()->plusScore($userInfo['uid'], 5) === true) {
          //登录送积分日志
          MembersActionModel::model()->addLoginAction($userInfo['uid']);
          }
          } */
        //明文密码
        $userInfo['expresslyPassword'] = $password;
        return $this->registerLogin($userInfo);
    }

    /**
     * 注册用户登录状态
     * @param array $user 用户基本信息
     * @param type $is_remeber_me 有效期，秒
     * @return boolean
     */
    public function registerLogin($user, $is_remeber_me = 604800) {
        if (is_object($user) && $user instanceof MembersModel) {
            $user = $user->attributes;
        }

        if (empty($user)) {
            return false;
        }
        //更新最后登录时间
        $model = MembersModel::model()->findByPk($user['uid']);
        $model->lastloginip = GuestDataModel::model()->getForwardedForIp();
        $model->lastlogintime = time();
        $model->save();
        //保持登录状态
        $cookie = new CHttpCookie(self::key, Encrypt::authcode($user['uid'], ''));
        //设置有效期
        $cookie->expire = time() + (int) $is_remeber_me;
        Yii::app()->request->cookies[self::key] = $cookie;
        //SSO单点同步登录
        TongbuSSO::getInstance()->login($user);
        return true;
    }

    /**
     * 注销登录状态
     * @return boolean
     */
    public function logout() {
        Yii::app()->request->getCookies()->remove(self::key);
        //SSO单点同步退出
        TongbuSSO::getInstance()->logout($user);
        return true;
    }

    /**
     * 根据提示符(username)和未加密的密码(密码为空时不参与验证)获取本地用户信息
     * @param type $identifier 为数字时，表示uid，其他为用户名
     * @param type $password 明文密码
     * @return boolean 成功返回用户信息array()，否则返回布尔值false
     */
    public function getLocalUser($identifier, $password = null) {
        if (empty($identifier)) {
            return false;
        }
        $model = MembersModel::model();
        $userInfo = $model->getUserInfo($identifier);
        if (empty($userInfo)) {
            $this->error = '该用户不存在！';
            return false;
        }
        //密码验证
        if (!empty($password)) {
            if ($model->hashPassword($password) != $userInfo['password']) {
                $this->error = '帐号密码错误！';
                return false;
            }
        }
        //去除敏感
        unset($userInfo['password']);
        return $userInfo;
    }

    public function offsetExists($index) {
        return isset(self::$userInfo[$index]);
    }

    public function offsetGet($index) {
        return self::$userInfo[$index];
    }

    public function offsetSet($index, $newvalue) {
        
    }

    public function offsetUnset($index) {
        
    }

}
